class HostsController < ApplicationController
  before_filter :authenticate_user!
  skip_before_filter :verify_authenticity_token, :only => [:set_attribute]

  def torrents_activate
    @host = Host.find(params[:id])
    @host.torrents_activate
    sleep 1
    flash[:notice] = @host.torrents_active? ? "Activated!" : "Fail monitoring this host - is utorrent agent running?"
    redirect_to :back
  end

  def torrents_deactivate
    @host = Host.find(params[:id])
    @host.torrents_deactivate
    flash[:notice] = "deactivated!"
    redirect_to :back
  end

  def index
    @hosts = Host.all
  end

  def new
    @host = Host.new
  end

  def edit
    @host = Host.find(params[:id])
  end

  def set_attribute
    host = Host.find(params[:id])
    attr = params[:attribute]
    val = params[:value] 
    raise "Missing parameters" unless attr and val and host

    begin
      host.send("set_#{attr}", val)
      flash[:notice] = "Configuration saved!"
    rescue
      flash[:notice] = "Something went wrong!"
    end
    redirect_to :back
  end

  def create
    @host = Host.new(params[:host])

    if @host.save
      flash[:notice] = "Host successfuly created"
      redirect_to edit_host_path(@host)
    else
      redirect_to :back
    end
  end

  def update
    @host = Host.find(params[:id])
    @host.update_attributes(params[:host])
    flash[:notice] = "Host information updated"
    redirect_to :back
  end

  def destroy
    @host = Host.find(params[:id])
    @host.destroy
    flash[:notice] = "Host destroyed"
    redirect_to :back
  end
end
